package com.neiquan.backstage.resourec_manage.webaction;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.Configs;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.common.util.Strings;
import com.neiquan.backstage.common.util.weixin.XMLParser;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.Lease;
import com.neiquan.backstage.pub.bsc.dao.po.Payment;
import com.neiquan.backstage.pub.bsc.dao.po.PlatformAllianceMember;
import com.neiquan.backstage.pub.bsc.dao.po.Station;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;
import com.neiquan.backstage.resourec_manage.PaymentService;
import com.neiquan.backstage.resourec_manage.ResourecLeaseService;
import com.neiquan.backstage.resourec_manage.ResourecStationService;
import com.neiquan.backstage.user.UserService;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;

@Controller
@RequestMapping(value = "paymentAction", produces = { "text/json;charset=UTF-8" })
public class PaymentAction {
	private static Class<?> poc = Lease.class;
	private static Class<?> pocS = Station.class;
	private static Class<?> pocE = Entrepreneur.class;
	private static Class<?> pocP = Payment.class;
	private static Class<?> pocM = PlatformAllianceMember.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private ResourecLeaseService resourecLeaseService;
	@Autowired
	private ResourecStationService resourecStationService;
	@Autowired
	private UserService userService;

	@ResponseBody
	@RequestMapping(value = "wxPay")
	public String myPay(HttpServletRequest request, int monthNumber, String endTime, int leaseId, double totalPrice, String body, HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		String openId = user.getWeixin_openid();
		if (openId == null) {
			openId = (String) Sessions.getLoginedOpinId(session);
		}
		Integer memberId = user.getMemberId();
		PlatformAllianceMember entityPF = extraSpringHibernateTemplate.findFirstOneByPropEq(pocM, "memberId", memberId);
		WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
		wxMpInMemoryConfigStorage.setAppId(entityPF.getWeixinAppId());
		wxMpInMemoryConfigStorage.setSecret(entityPF.getWeixinAppSecret());
		wxMpInMemoryConfigStorage.setToken(entityPF.getWeixinToken());
		wxMpInMemoryConfigStorage.setAesKey(entityPF.getWeixinEncodingAesKey());
		wxMpInMemoryConfigStorage.setPartnerId(entityPF.getWeixinMchId());
		wxMpInMemoryConfigStorage.setPartnerKey(entityPF.getWeixinSignKey());
		WxMpService wxm = new WxMpServiceImpl();
		wxm.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
		String website = entityPF.getWebsite();// 站点回掉用
		double amt = 0.01; // 金钱
		String tradeType = "JSAPI";// 类型
		String ip = request.getRemoteAddr();// 获取主机ip
		String project_name = Configs.get().getString("system.project_name");
		String notifyUrl = String.format("%s/%s/api/paymentAction/payWiexin", website, project_name);
		wxm.setWxMpConfigStorage(wxMpInMemoryConfigStorage);
		String outTradeNo = UUID.randomUUID().toString().replace("-", "");
		Map<String, String> jssdkPayInfo = wxm.getJSSDKPayInfo(openId, outTradeNo, amt, body, tradeType, ip, notifyUrl);
		// 添加支付表
		Payment entityPm = new Payment();
		String entrepreneurUniqueId = user.getEntrepreneurUniqueId();
		Integer userId = user.getUserId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(entrepreneurUniqueId, memberId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		long time = simpleDateFormat.parse(endTime).getTime();
		entityPm.setEndTime(time);
		entityPm.setEntrepreneurId(entrepreneurId);
		entityPm.setLeaseId(leaseId);
		entityPm.setMode(Payment.PAY_LINE_ON);
		entityPm.setMonthNumber(monthNumber);
		entityPm.setUserId(userId);
		entityPm.setUUID(outTradeNo);
		entityPm.setStratTime(System.currentTimeMillis());
		entityPm.setTotalRent(totalPrice);
		entityPm.setStatus(Payment.PAY_WAIT);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entityPm);
		return CommonResp.buildSuccessResp(jssdkPayInfo).toJsonString();
	}

	@RequestMapping(value = "payWiexin")
	public String payWiexin(HttpServletRequest request) throws Exception, ParserConfigurationException, SAXException {
		String inputLine;
		String notityXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> mapFromXML = XMLParser.getMapFromXML(notityXml);
		String out_trade_no = (String) mapFromXML.get("out_trade_no");
		String result_code = (String) mapFromXML.get("result_code");
		String total_fee = (String) mapFromXML.get("total_fee");
		if (result_code.equals("SUCCESS")) {
			Payment entityP = paymentService.querByUUID(out_trade_no);
			Integer status = entityP.getStatus();
			if (status == Payment.PAY_WAIT) {
				String format = new DecimalFormat("#.00").format(Double.parseDouble(total_fee) / 100);
				entityP.setTotalRent(Double.parseDouble(format));
				entityP.setStatus(Payment.PAY_SUCCEE);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityP);
				Integer leaseId = entityP.getLeaseId();
				Lease entityL = resourecLeaseService.queryById(leaseId);
				Integer newlyStuats = entityL.getNewlyStuats();
				Integer status2 = entityL.getStatus();
				if (newlyStuats == Lease.new_yes && status2 == Lease.status_pass) {
					Integer entrepreneurId = entityL.getEntrepreneurId();
					List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_no, Lease.status_pass);
					if (listL.size() > 0) {
						Lease entityLNP = listL.get(0);
						Integer leaseIdNP = entityLNP.getLeaseId();
						double sumRental = entityLNP.getSumRental();
						String momentStationIds = entityLNP.getMomentStationIds();
						List<Station> listS = resourecStationService.queryAllByLeaseId(leaseId, Station.status_lease);
						for (Station s : listS) {
							sumRental += s.getRental();
							momentStationIds += "," + s.getStationId();
							s.setLeaseId(leaseIdNP);
							s.setState(Station.status_lease);
							extraSpringHibernateTemplate.getHibernateTemplate().update(s);
						}
						entityLNP.setMomentStationIds(momentStationIds);
						entityLNP.setSumRental(sumRental);
						extraSpringHibernateTemplate.getHibernateTemplate().update(entityLNP);
						extraSpringHibernateTemplate.getHibernateTemplate().delete(entityL);
					}
				}
			}
		} else {
			Payment entityP = paymentService.querByUUID(out_trade_no);
			Integer status = entityP.getStatus();
			if (status == Payment.PAY_WAIT) {
				String format = new DecimalFormat("#.00").format(Double.parseDouble(total_fee) / 100);
				entityP.setTotalRent(Double.parseDouble(format));
				entityP.setStatus(Payment.PAY_FAIL);
				extraSpringHibernateTemplate.getHibernateTemplate().update(entityP);
			}
		}
		return null;
	}

	/**
	 * 查看所有
	 */
	@ResponseBody
	@RequestMapping(value = { "allInfo" })
	public String allInfo(Integer id, HttpSession session) {
		User user = (User) Sessions.getLoginedUser(session);
		String uniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByEntrepreneurUnique(uniqueId);
		if (entityE == null) {
			return CommonResp.buildSuccessResp().toJsonString();
		}
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(entrepreneurId);
		List<Payment> listP = paymentService.queryByEentrepreneurId(entrepreneurId);
		HashMap<String, Object> map = new HashMap<>();
		map.put("listL", listL);
		map.put("listP", listP);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	/**
	 * 查看缴费记录
	 */
	@ResponseBody
	@RequestMapping(value = { "allRecord" })
	public String allRecord(Integer id) throws ParseException {
		List<Payment> listP = (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Payment where leaseId=? and status=?", id, Payment.PAY_SUCCEE);
		return CommonResp.buildSuccessResp(listP).toJsonString();
	}

	/**
	 * 查询新增出租表欠费情况
	 */
	@ResponseBody
	@RequestMapping(value = { "findPayment" })
	public String findPayment(Integer leaseId) throws ParseException {
		double needPayment = 0;
		Long endTime = null;
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		Long stratTime = entityL.getStratTime();
		double sumRental = entityL.getSumRental();
		Integer entrepreneurId = entityL.getEntrepreneurId();
		List<Lease> listL = (List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where entrepreneurId=? and newlyStuats=?", entrepreneurId, Lease.new_no);
		Lease lease2 = listL.get(0);
		Integer leaseId2 = lease2.getLeaseId();
		List<Payment> entityP = (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId2, Payment.PAY_SUCCEE);
		Map<String, Object> map = new HashMap<String, Object>();
		if (entityP.size() <= 0) {
			Lease lease = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
			// endTime=lease.getStratTime();
			// map.put("needPayment", String.format("%.2f", needPayment));
			// map.put("endTime1", endTime);
			return CommonResp.buildSuccessResp("null").toJsonString();
		} else {
			Payment payment = entityP.get(0);
			int payLeaseId = payment.getLeaseId();
			Lease lease = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
			endTime = payment.getEndTime();
		}
		int numberMonth = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(endTime);
		int currentYear = calendar.get(Calendar.YEAR);
		int currentMonth = calendar.get(Calendar.MONTH);
		int currentDay = calendar.get(Calendar.DATE);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.YEAR, currentYear);
		calendar2.set(Calendar.MONTH, currentMonth - 1);
		calendar2.set(Calendar.DATE, 1);
		calendar2.roll(Calendar.DATE, -1);
		int currentDayNum = calendar2.get(Calendar.DATE);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeInMillis(stratTime);
		int endYear = calendar1.get(Calendar.YEAR);
		int endMonth = calendar1.get(Calendar.MONTH);
		int endDay = calendar1.get(Calendar.DATE);
		if (currentYear == endYear) {
			if (currentMonth == endMonth) {
				if (currentDay > endDay) {
					int day = currentDay - endDay;
					needPayment = sumRental * day / currentDayNum;
				}
			}
			if (currentMonth > endMonth) {
				int a = currentMonth - endMonth;
				if (currentDay > endDay) {
					numberMonth = a;
					int day = currentDay - endDay;
					needPayment = (a * sumRental) + (sumRental * day / currentDayNum);
				} else {
					numberMonth = a - 1;
					int day = endDay - currentDay;
					needPayment = (a * sumRental) - (sumRental * day / 30);
				}
			}
		} else if (currentYear > endYear) {
			Integer b = currentYear - endYear;
			numberMonth = b * 12 + currentMonth - endMonth;
			if (currentDay > endDay) {
				int day = currentDay - endDay;
				numberMonth = b * 12 + currentMonth - endMonth + 1;
				needPayment = (numberMonth * sumRental) + (sumRental * day / 30);
			} else {
				int day = endDay - currentDay;
				numberMonth = b * 12 + currentMonth - endMonth;
				needPayment = (numberMonth * sumRental) - (sumRental * day / 30);
				;
			}
		}
		map.put("needPayment", String.format("%.2f", needPayment));
		map.put("endTime1", endTime);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	/**
	 * 查询是否欠费
	 */
	@ResponseBody
	@RequestMapping(value = { "firstPayment" })
	public String firstPayment(HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		String entrepreneurUniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByEntrepreneurUnique(entrepreneurUniqueId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Lease> listL = resourecLeaseService.queryByEntrepreneurId(entrepreneurId, Lease.new_no, Lease.status_pass);
		if (listL.size() <= 0) {
			return CommonResp.buildSuccessResp(BackendErrorCode.unknown_error).toJsonString();
		}
		Lease netityNOP = listL.get(0);
		Integer leaseId = netityNOP.getLeaseId();
		double arrearage = 0;
		double sumRental = 0;
		Long endTime = null;
		List<Payment> entityP = (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId, Payment.PAY_SUCCEE);
		Map<String, Object> map = new HashMap<String, Object>();
		if (entityP.size() <= 0) {
			Lease lease = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
			sumRental = lease.getSumRental();
			endTime = lease.getStratTime();
		} else {
			Payment payment = entityP.get(0);
			int payLeaseId = payment.getLeaseId();
			Lease lease = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
			sumRental = lease.getSumRental();
			endTime = payment.getEndTime();
		}
		int numberMonth = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		int currentYear = calendar.get(Calendar.YEAR);
		int currentMonth = calendar.get(Calendar.MONTH);
		int currentDay = calendar.get(Calendar.DATE);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.YEAR, currentYear);
		calendar2.set(Calendar.MONTH, currentMonth - 1);
		calendar2.set(Calendar.DATE, 1);
		calendar2.roll(Calendar.DATE, -1);
		int currentDayNum = calendar2.get(Calendar.DATE);
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeInMillis(endTime);
		int endYear = calendar1.get(Calendar.YEAR);
		int endMonth = calendar1.get(Calendar.MONTH);
		int endDay = calendar1.get(Calendar.DATE);
		if (currentYear == endYear) {
			if (currentMonth == endMonth) {
				if (currentDay > endDay) {
					int day = currentDay - endDay;
					arrearage = sumRental * day / currentDayNum;
				}
			}
			if (currentMonth > endMonth) {
				int a = currentMonth - endMonth;
				if (currentDay > endDay) {
					numberMonth = a;
					int day = currentDay - endDay;
					arrearage = (a * sumRental) + (sumRental * day / currentDayNum);
				} else {
					numberMonth = a - 1;
					int day = endDay - currentDay;
					arrearage = (a * sumRental) - (sumRental * day / currentDayNum);
				}
			}
		} else if (currentYear > endYear) {
			Integer b = currentYear - endYear;
			numberMonth = b * 12 + currentMonth - endMonth;
			if (currentDay > endDay) {
				int day = currentDay - endDay;
				numberMonth = b * 12 + currentMonth - endMonth + 1;
				arrearage = (numberMonth * sumRental) + (sumRental * day / currentDayNum);
			} else {
				int day = endDay - currentDay;
				numberMonth = b * 12 + currentMonth - endMonth;
				arrearage = (numberMonth * sumRental) - (sumRental * day / currentDayNum);
				;
			}
		}
		map.put("numberMonth", numberMonth);
		map.put("arrearage", String.format("%.2f", arrearage));
		map.put("endTime", endTime);
		return CommonResp.buildSuccessResp(map).toJsonString();
	}

	/**
	 * 添加付款对象
	 */
	@ResponseBody
	@RequestMapping(value = { "addPayment" })
	public String addPayment(Integer leaseId, double totalRent, long rentTime, Integer monthNumber) throws ParseException {
		Payment entityP = new Payment();
		entityP.setLeaseId(leaseId);
		entityP.setMonthNumber(monthNumber);
		entityP.setStratTime(System.currentTimeMillis());
		entityP.setTotalRent(totalRent);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(rentTime);
		calendar.add(Calendar.MONTH, +monthNumber);
		long endTime = calendar.getTimeInMillis();
		entityP.setEndTime(endTime);
		entityP.setMode(Payment.PAY_LINE_BELOW);
		entityP.setStatus(Payment.PAY_SUCCEE);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entityP);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 恢复更换失败状态为正常状态
	 */
	@ResponseBody
	@RequestMapping(value = { "recoverChange" })
	public String recoverChange(Integer leaseId) {
		Lease entityL = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		entityL.setStatus(1);
		extraSpringHibernateTemplate.getHibernateTemplate().update(entityL);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 通过公司名查询该公司下lesaeId
	 */
	@ResponseBody
	@RequestMapping(value = { "queryByEntNamelesaeId" })
	public String queryByEntNamelesaeId(String name) {
		Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "name", name);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		List<Station> find = (List<Station>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Station s WHERE entrepreneur=? AND status==1", entrepreneurId);
		Station station = find.get(0);
		return CommonResp.buildSuccessResp(station).toJsonString();
	}

	/**
	 * 查询指定是lease对象
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "queryLease" })
	public String queryLease(Integer leaseId) {
		Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		return CommonResp.buildSuccessResp(entity).toJsonString();
	}

	/**
	 * 查询指定是Entrepreneur对象
	 */
	@ResponseBody
	@RequestMapping(value = { "queryEntrepreneur" })
	public String queryEntrepreneur(Integer leaseId) {
		// TODO Auto-generated method stub
		Lease entity = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "leaseId", leaseId);
		Integer entrepreneurId = entity.getEntrepreneurId();
		Entrepreneur entrepreneur = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
		return CommonResp.buildSuccessResp(entrepreneur).toJsonString();
	}

	/**
	 * 查询去重是zone对象
	 */
	@ResponseBody
	@RequestMapping(value = { "queryStations" })
	public String queryStations(Integer leaseId) {
		// TODO Auto-generated method stub
		List<Station> find = extraSpringHibernateTemplate.findAllByPropEq(pocS, "leaseId", leaseId);
		return CommonResp.buildSuccessResp(find).toJsonString();
	}

	/**
	 * 查看欠费
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "listArrearage" })
	public String listArrearage(HttpSession session) {
		List list = new ArrayList();
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Lease> entitysL = (List<Lease>) extraSpringHibernateTemplate.getHibernateTemplate().find("From Lease where memberId=?", memberId);
		if (entitysL == null || entitysL.size() <= 0) {
			return CommonResp.buildSuccessResp().toJsonString();
		} else {
			for (Lease lease : entitysL) {
				int status = 0;
				Integer leaseId = lease.getLeaseId();
				Long endTime1 = lease.getEndTime();
				Payment entityP1 = extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "leaseId", leaseId);
				if (entityP1 == null) {
					status = 1;
				}
				Integer newlyStuats = lease.getNewlyStuats();
				String phone = "";
				String name = "";
				double arrearage = 0;
				double sumRental = 0;
				Long endTime = null;
				List<Payment> entityP = (List<Payment>) extraSpringHibernateTemplate.getHibernateTemplate().find("FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)", leaseId, Payment.PAY_SUCCEE);
				Map<String, Object> map = new HashMap<String, Object>();
				if (entityP.size() <= 0) {
					Lease lease1 = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", leaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if (entityE == null) {
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone = entityE.getPhone();
					name = entityE.getName();
					sumRental = lease1.getSumRental();
					endTime = lease1.getStratTime();// 可能有bug
				} else {
					Payment payment = entityP.get(0);
					int payLeaseId = payment.getLeaseId();
					Lease lease1 = extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class, "leaseId", payLeaseId);
					Integer entrepreneurId = lease1.getEntrepreneurId();
					Entrepreneur entityE = extraSpringHibernateTemplate.findFirstOneByPropEq(pocE, "entrepreneurId", entrepreneurId);
					if (entityE == null) {
						return CommonResp.buildSuccessResp().toJsonString();
					}
					phone = entityE.getPhone();
					name = entityE.getName();
					sumRental = lease1.getSumRental();
					endTime = payment.getEndTime();
				}
				int numberMonth = 0;
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				int currentDayNum = calendar.get(Calendar.DAY_OF_MONTH);
				int currentYear = calendar.get(Calendar.YEAR);
				int currentMonth = calendar.get(Calendar.MONTH);
				int currentDay = calendar.get(Calendar.DATE);
				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTimeInMillis(endTime);
				int endYear = calendar1.get(Calendar.YEAR);
				int endMonth = calendar1.get(Calendar.MONTH);
				int endDay = calendar1.get(Calendar.DATE);
				if (currentYear == endYear) {
					if (currentMonth == endMonth) {
						if (currentDay > endDay) {
							int day = currentDay - endDay;
							arrearage = sumRental * day / currentDayNum;
						}
					}
					if (currentMonth > endMonth) {
						int a = currentMonth - endMonth;
						if (currentDay > endDay) {
							numberMonth = a;
							int day = currentDay - endDay;
							arrearage = (a * sumRental) + (sumRental * day / currentDayNum);
						} else {
							numberMonth = a - 1;
							int day = endDay - currentDay;
							arrearage = (a * sumRental) - (sumRental * day / 30);
						}
					}
				} else if (currentYear > endYear) {
					Integer b = currentYear - endYear;
					numberMonth = b * 12 + currentMonth - endMonth;
					if (currentDay > endDay) {
						int day = currentDay - endDay;
						numberMonth = b * 12 + currentMonth - endMonth + 1;
						arrearage = (numberMonth * sumRental) + (sumRental * day / 30);
					} else {
						int day = endDay - currentDay;
						numberMonth = b * 12 + currentMonth - endMonth;
						arrearage = (numberMonth * sumRental) - (sumRental * day / 30);
						;
					}
				}
				if (arrearage > 0) {
					map.put("status", status);
					map.put("newlyStuats", newlyStuats);
					map.put("leaseId", leaseId);
					map.put("phone", phone);
					map.put("name", name);
					map.put("numberMonth", numberMonth);
					map.put("arrearage", String.format("%.2f", arrearage));
					map.put("endTime", endTime);
					map.put("endTime1", endTime1);
					list.add(map);
				}
			}
			return CommonResp.buildSuccessResp(list).toJsonString();
		}
	}

	/**
	 * 分页查询所有
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 *//*
		 * @ResponseBody
		 * 
		 * @RequestMapping(value={"list"}) public String list(int pageIndex, int
		 * pageSize,HttpSession session){ List list=new ArrayList(); AdminUser
		 * loginedUser = (AdminUser) Sessions.getLoginedUser(session); Integer
		 * memberId = loginedUser.getMemberId(); List<Lease>
		 * entitysL=(List<Lease>)
		 * extraSpringHibernateTemplate.getHibernateTemplate().find(
		 * "From Lease where memberId=?", memberId);
		 * if(entitysL==null||entitysL.size()<=0){ return
		 * CommonResp.buildSuccessResp().toJsonString(); }else{ for(Lease
		 * lease:entitysL){ int status=0; Integer leaseId = lease.getLeaseId();
		 * Long endTime1 = lease.getEndTime(); Payment entityP1 =
		 * extraSpringHibernateTemplate.findFirstOneByPropEq(pocP, "leaseId",
		 * leaseId); if(entityP1==null){ status=1; } Integer newlyStuats =
		 * lease.getNewlyStuats(); String phone=""; String name=""; double
		 * arrearage=0; double sumRental=0; Long endTime=null; List<Payment>
		 * entityP=(List<Payment>)
		 * extraSpringHibernateTemplate.getHibernateTemplate() .find(
		 * "FROM Payment WHERE endTime=(SELECT MAX(endTime) FROM Payment WHERE leaseId=? and status=?)"
		 * , leaseId,Payment.PAY_SUCCEE); Map<String, Object> map=new
		 * HashMap<String, Object>(); if(entityP.size()<=0){ Lease
		 * lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class,
		 * "leaseId", leaseId); Integer entrepreneurId =
		 * lease1.getEntrepreneurId(); Entrepreneur entityE =
		 * extraSpringHibernateTemplate.findFirstOneByPropEq(pocE,
		 * "entrepreneurId", entrepreneurId); if(entityE==null){ return
		 * CommonResp.buildSuccessResp().toJsonString(); }
		 * phone=entityE.getPhone(); name=entityE.getName(); sumRental =
		 * lease1.getSumRental(); endTime=lease1.getStratTime();//可能有bug }else{
		 * Payment payment = entityP.get(0); int
		 * payLeaseId=payment.getLeaseId(); Lease
		 * lease1=extraSpringHibernateTemplate.findFirstOneByPropEq(Lease.class,
		 * "leaseId", payLeaseId); Integer entrepreneurId =
		 * lease1.getEntrepreneurId(); Entrepreneur entityE =
		 * extraSpringHibernateTemplate.findFirstOneByPropEq(pocE,
		 * "entrepreneurId", entrepreneurId); if(entityE==null){ return
		 * CommonResp.buildSuccessResp().toJsonString(); }
		 * phone=entityE.getPhone(); name=entityE.getName(); sumRental =
		 * lease1.getSumRental(); endTime = payment.getEndTime(); } int
		 * numberMonth=0; Calendar calendar = Calendar.getInstance();
		 * calendar.setTimeInMillis(System.currentTimeMillis()); int
		 * currentDayNum=calendar.get(Calendar.DAY_OF_MONTH); int currentYear =
		 * calendar.get(Calendar.YEAR); int currentMonth =
		 * calendar.get(Calendar.MONTH); int
		 * currentDay=calendar.get(Calendar.DATE); Calendar calendar1 =
		 * Calendar.getInstance(); calendar1.setTimeInMillis(endTime); int
		 * endYear = calendar1.get(Calendar.YEAR); int endMonth =
		 * calendar1.get(Calendar.MONTH); int
		 * endDay=calendar1.get(Calendar.DATE); if(currentYear==endYear){
		 * if(currentMonth==endMonth){ if(currentDay>endDay){ int
		 * day=currentDay-endDay; arrearage=sumRental*day/currentDayNum; } }
		 * if(currentMonth>endMonth){ int a=currentMonth-endMonth;
		 * if(currentDay>endDay){ numberMonth=a; int day=currentDay-endDay;
		 * arrearage=(a*sumRental)+(sumRental*day/currentDayNum); }else{
		 * numberMonth=a-1; int day=endDay-currentDay;
		 * arrearage=(a*sumRental)-(sumRental*day/30); } } }else
		 * if(currentYear>endYear){ Integer b=currentYear-endYear;
		 * numberMonth=b*12+currentMonth-endMonth; if(currentDay>endDay){ int
		 * day=currentDay-endDay; numberMonth=b*12+currentMonth-endMonth+1;
		 * arrearage=(numberMonth*sumRental)+(sumRental*day/30); }else{ int
		 * day=endDay-currentDay; numberMonth=b*12+currentMonth-endMonth;
		 * arrearage=(numberMonth*sumRental)-(sumRental*day/30);; } }
		 * map.put("status", status); map.put("newlyStuats", newlyStuats);
		 * map.put("leaseId", leaseId); map.put("phone", phone); map.put("name",
		 * name); map.put("numberMonth", numberMonth); map.put("arrearage",
		 * String.format("%.2f", arrearage)); map.put("endTime", endTime);
		 * map.put("endTime1", endTime1); list.add(map); } return
		 * CommonResp.buildSuccessResp(list).toJsonString(); } }
		 */
	/**
	 * 添加出租对象
	 * 
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = { "addLease" })
	public String addLease(@RequestParam("stationIds[]") Integer[] stationIds, Integer monthNumber, double totalPrice, String endTime, String startTime, Integer entrepreneurId, double sumRental, HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		Lease entity = new Lease();
		Lease lease = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "entrepreneurId", entrepreneurId);
		if (lease != null) {
			entity.setStatus(5);
		} else {
			entity.setStatus(0);
		}
		entity.setMonthNumber(monthNumber);
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		entity.setStratTime(dateFormat.parse(Strings.trimAndNotNull(startTime)).getTime());
		entity.setEndTime(dateFormat.parse(Strings.trimAndNotNull(endTime)).getTime());
		entity.setEntrepreneurId(entrepreneurId);
		entity.setTotalPrice(totalPrice);
		entity.setSumRental(sumRental);
		String momentStationIds = "";
		for (Integer stationId1 : stationIds) {
			momentStationIds += stationId1 + ",";
		}
		entity.setMemberId(memberId);
		entity.setMomentStationIds(momentStationIds);
		extraSpringHibernateTemplate.getHibernateTemplate().save(entity);
		Lease entity1 = extraSpringHibernateTemplate.findFirstOneByPropEq(poc, "entrepreneurId", entrepreneurId);
		Integer leaseId = entity1.getLeaseId();
		for (Integer stationId : stationIds) {
			Station entityS = extraSpringHibernateTemplate.findFirstOneByPropEq(pocS, "stationId", stationId);
			entityS.setLeaseId(leaseId);
			entityS.setState(3);
			extraSpringHibernateTemplate.getHibernateTemplate().update(entityS);
		}

		return CommonResp.buildSuccessResp().toJsonString();
	}

	/**
	 * 查询所有queryAll zone group by去重
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "queryAll" })
	public String queryAll(HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		DetachedCriteria dc = DetachedCriteria.forClass(Station.class);
		dc.add(Restrictions.eq("memberId", memberId));
		dc.setProjection(Projections.alias(Projections.groupProperty("zone"), "zone"));
		List<Station> list = extraSpringHibernateTemplate.findAllByCriteria(dc);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}

	/**
	 * 生成工位图
	 * 
	 * @param zone
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "stationImg" })
	public String stationImg(String zone, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", memberId));
		criterions.add(Restrictions.eq("zone", zone));
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.build(Station.class, criterion);
		List<Station> list = extraSpringHibernateTemplate.findAllByCriteria(queryCountCriteria);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}

}
